package com.itheima.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.api.UserApi;
import com.itheima.api.UserInfoApi;
import com.itheima.api.VideoApi;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.domain.UserInfo;
import com.itheima.domain.Video;
import com.itheima.server.exception.BusinessException;
import com.itheima.server.exception.ErrorResult;
import com.itheima.server.interceptor.UserHolder;
import com.itheima.utils.Constants;
import com.itheima.vo.PageResult;
import com.itheima.vo.VideoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideoService {

    @Resource
    private FastFileStorageClient fastFileStorageClient;

    @Resource
    private FdfsWebServer fdfsWebServer;

    @Resource
    private OssTemplate ossTemplate;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 上传小视频
     * @param videoThumbnail
     * @param videoFile
     */
    public void uploadVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        if (videoFile.isEmpty() || videoThumbnail.isEmpty()){
            throw new BusinessException(ErrorResult.error());
        }
        String filename = videoFile.getOriginalFilename();
        //截取后缀名
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        //上传fastDFS
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        //视频访问路径
        String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //把封面图上传oss
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)){
            throw new BusinessException(ErrorResult.error());
        }

    }

    /**
     * 获取小视频列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult downLoadVideo(Integer page, Integer pagesize) {
        //从redis中获取推荐视频列表
        String redisVideoStr = redisTemplate.opsForValue().get(Constants.VIDEOS_RECOMMEND + UserHolder.getUserId());
        int redisPages = 0;
        List<Video> videos = new ArrayList<>();
        if (redisVideoStr != null){
            String[] split = redisVideoStr.split(",");
            List<Long> pids = Arrays.stream(split).map(Long::parseLong).collect(Collectors.toList());
            //判断是否满足分页条件
            if ((page - 1) * pagesize < pids.size()){
                pids  = pids.stream().skip((long) (page - 1) * pagesize).limit(pagesize).collect(Collectors.toList());
                //去查
                videos = videoApi.getVideo(pids);
            }
            redisPages = PageUtil.totalPage(split.length,pagesize);
        }

        //redis中没有数据，直接去分页查询
        if (videos.isEmpty()){
            //redis中没查到，说明已经查到redis中最后一页了，因此page - redisPages = 1
           videos = videoApi.getByPage(page - redisPages,pagesize);
        }
        List<Long> userIds = videos.stream().map(Video::getUserId).collect(Collectors.toList());
        Map<Long, UserInfo> userInfos = userInfoApi.getByIds(userIds, null);
        List<VideoVo> list = new ArrayList<>();
        for (Video video : videos) {
            UserInfo userInfo = userInfos.get(video.getUserId());
            if (userInfo != null){
                VideoVo vo = VideoVo.init(userInfo, video);
                list.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,list);
    }

}
